//
//  CameraView.swift
//  WatermarkCamera
//
//  Created by AxcLogo on 4/7/2024.
//

import UIKit
import AxcBedrock

class CameraView: UIView {
    // Lifecycle

    convenience init() {
        self.init(frame: .zero)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        config()

        createUI()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) 未实现")
    }

    // Open

    /// 摄像头即将切换
    var willRotateCameraBlock: AxcBlock.OneParam<Camera.Position>? {
        didSet { camera.willRotateCameraBlock = willRotateCameraBlock }
    }

    /// 摄像头已经完成切换
    var didRotateCameraBlock: AxcBlock.OneParam<Camera.Position>? {
        didSet { camera.didRotateCameraBlock = didRotateCameraBlock }
    }

    func config() {
        eyepiece.setInput(.camera(camera))

        eyepiece.appendOutputs([
            previewView,

            videoWriter,

            imageWriter,

            videoBuffer,

        ])
    }

    func createUI() {
        addSubview(previewView)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        previewView.frame = bounds
    }

    // Internal

    // MARK: 输入端

    /// 相机
    lazy var camera: Camera = {
        let camera = Camera()

        return camera
    }()

    // MARK: 处理端

    /// 墨镜
    lazy var eyepiece: Eyepiece = {
        let eyepiece = Eyepiece()

        return eyepiece
    }()

    // MARK: 输出端

    /// 预览采集
    lazy var previewView: PreviewView = {
        let view = PreviewView()

        return view
    }()

    /// 视频采集
    lazy var videoWriter: VideoWriter = {
        let writer = VideoWriter()

        writer.addWriterBlock = { [weak self] writer in // 将相机的音频绑定到采集

            guard let weakSelf = self else { return }

            weakSelf.camera.gpuCamera.audioEncodingTarget = writer
        }

        writer.removeWriterBlock = { [weak self] in // 将相机的音频取消绑定

            guard let weakSelf = self else { return }

            weakSelf.camera.gpuCamera.audioEncodingTarget = nil
        }

        return writer
    }()

    /// 图像采集
    lazy var imageWriter: ImageWriter = {
        let writer = ImageWriter()

        return writer
    }()

    /// 流采集
    lazy var videoBuffer: VideoBuffer = {
        let buffer = VideoBuffer()

        return buffer
    }()

    /// 写入清晰度
    var _writerArticulation: VideoBuffer.Articulation = ._720p
    
    
    /// 水印数量
    func watermarkCount() -> Int {
        return eyepiece.watermarkCount()
    }
}
